<?php
		
	/* SVN FILE: $Id: fnTags.php 8 2011-03-13 08:32:38Z michele.andreoletti@gmail.com $ */
	
	/**
	 * Project Name : arcadia
	 *
	 * @author $Author: michele.andreoletti@gmail.com $
	 * @version $Revision: 8 $
	 * @lastrevision $Date: 2011-03-13 08:32:38 +0000 (Sun, 13 Mar 2011) $
	 * @filesource $URL: http://arcadia.googlecode.com/svn/trunk/include/fnTags.php $
	 */


	/**
	 *
	 * fnTagsView
	 * E' possibile impostare per la variabile $sWhat il valore 'view' oppure il valore 'main-table'.
	 * Se $sWhat == 'main-table', è possibile impostare la variabile $iView a 0 (e di conseguenza anche $iTrash
	 * può essere lasciata uguale a 0). La variabile $iTrash indica se il record relativo a $iView
	 * è una scheda spostata nel cestino (ovvero: cancellata).
	 *
	 */
	function fnTagsView ($sWhat, $iView=0, $sViewItemLink, $sTable, $sTag, $sApp, $bCompactView=false, $bEditAllowed=true, $bTagsSelectInputShow=true) {
		
		$html = '';
		
		if (empty($sViewItemLink) && !empty($sTable)) {
			global $aTABLE;
			if (isset($aTABLE[$sTable]['sViewItemLink'])) {
				$sViewItemLink =  $aTABLE[$sTable]['sViewItemLink'];
			} else  {
				die('ERROR: sViewItemLink not defined');
			}
		}
		
		if (empty($iView)) {
			$iAccessLvl = fnGetAccessLvl();		
		} else {
			global $aTABLE;
			global $aTABLE_SECURITY_CHECK;
			$iAccessLvl = fnViewAccessLvl($iView, $aTABLE, $aTABLE_SECURITY_CHECK);
		}
		
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, '', 0, 'tags');
		
		global $aVIEW;		
		
		if (empty($iView) || fnCheckViewTrashed($iView, $aVIEW[$sViewItemLink]['sViewSelectFrom'], $aVIEW[$sViewItemLink]['sViewSelectGroupBy'])) {
			// quando si sta creando una nuova scheda o quando una scheda è nel cestino non è
			// possibile effettuare nessuna modifica (quindi il livello massimo assegnabile a
			// $iFieldAccessLvl è 1).
			$iFieldAccessLvl = min($iFieldAccessLvl, 1);
		}

		if (isset($aVIEW[$sViewItemLink]['sTagsType'])) {
			$sTagsType = $aVIEW[$sViewItemLink]['sTagsType'];
		} else  {
			die('ERROR: sTagsType not defined');
		}
		
		if (isset($aVIEW[$sViewItemLink]['sViewSelectFrom'])) {
			$sViewSelectFrom = $aVIEW[$sViewItemLink]['sViewSelectFrom'];
		} else  {
			die('ERROR: sViewSelectFrom not defined');
		}

		if (is_allowed('view', $iFieldAccessLvl)) {
			
			$aTag = explode ('|', $sTag);
			
			if ($sWhat == 'view' && !empty($iView)) {								
				$sQuery = fnTagsLinkedQuery($sWhat, $iView, $sViewItemLink, $sApp, $bCompactView);
				$rResult = custom_mysql_query($sQuery, 'fnTagsLinkedQuery()');
			
			} else if ($sWhat == 'main-table')  {
				$id = 'tags-selectable';	
				$sQuery = fnTagsAllQuery($sTagsType, $bCompactView);
				$rResult = custom_mysql_query($sQuery, 'fnTagsAllQuery()');
			
			}

			if ($sWhat == 'main-table')  {
				$html .= "	<div id='tags-reset'><em>tutte le categorie</em></div>
							<div style='clear: both'></div>";
			}
			
			$html .= "<ol class='tags-$sWhat' ".($sWhat == 'main-table' ? " id='tags-selectable' " : '').">";
			
			if (isset($rResult) && mysql_num_rows($rResult) > 0) {

				while ($aRow = mysql_fetch_array($rResult)) {
				
					if ($sWhat == 'view') {		
						$html .= "<li style='".$aRow['sStyle']."'>";	
					} else if ($sWhat == 'main-table')  {
						$html .= "<li iTag='".($aRow['iTag'])."' class='ui-widget-content ".(in_array($aRow['iTag'], $aTag) ? ' ui-selected' : '')."'>";
					}
					
					if (!$bCompactView) {
						$html .= "<span class='sDescription'>".$aRow['sDescription']."</span>";
					} else {
						$html .= "<span class='sDescription'>".$aRow['sDescriptionCompactView']."</span>";
					}
					
					if ($sWhat == 'view' && is_allowed('edit', $iFieldAccessLvl) && $bEditAllowed) {
						$html .= "<span class='tags-remove-spacer'>|</span><span class='tags-remove' iTag='".($aRow['iTag'])."' iView='$iView' style='".$aRow['sStyle']."'>x</span>";
					}
					
					$html .= "</li>";
				}
				
			}
			
			if ($sWhat == 'main-table')  {
				$html .= "<li iTag='0' class='ui-widget-content ".(in_array("0", $aTag) ? ' ui-selected' : '')."'><em>Nessuna Categoria</em></li>";
			}

			if  ($sWhat == 'view' && is_allowed('edit', $iFieldAccessLvl) && $bEditAllowed && $bTagsSelectInputShow) {
				$html .= "<li style='border: 0px;'><span id='tags-loader' style='display:none;'><img src='../themes/common/images/indicator.gif' alt='Attendere...' /></span></li>";
				$html .= "<li style='border: 0px;'>".fnTagsSelInput('tags-sel-input', $iView, $sViewItemLink, $bCompactView)."</li>";
			}

			$html .= "</ol>";	
			
			if ($sWhat == 'main-table')  {
				$html .= "<input type='hidden' id='sTag' value='$sTag'>";
			}
			
		} else {
			$html .= "&nbsp;";
		}
		
		if ($sWhat == 'main-table') {
			if (is_allowed('sysop', $iAccessLvl) && fnShowDebugMsg()) {
				$html .= "<p id='tags-feedback'>Categorie selezionate: <span id='tags-select-result'></span></p>";	
			}
			$html .= "<br/>";	
		}

		return $html;
	}


	/**
	 *
	 * fnTagsLinkedQuery
	 *
	 */
	function fnTagsLinkedQuery ($sWhat, $mView, $sViewItemLink, $sApp, $bCompactView=true) {
		
		global $aVIEW;
		if (isset($aVIEW[$sViewItemLink]['sTagsType'])) {
			$sTagsType = $aVIEW[$sViewItemLink]['sTagsType'];
		} else  {
			die('ERROR: sTagsType not defined');
		}
		
		if (isset($aVIEW[$sViewItemLink]['sViewSelectFrom'])) {
			$sViewSelectFrom = $aVIEW[$sViewItemLink]['sViewSelectFrom'];
		} else  {
			die('ERROR: sViewSelectFrom not defined');
		}
		
		// visualizzo gli eventuali tag associati per cui iShow == 1
		
		if ($sWhat == 'view') {
			$sShow = " (`resources`.`iShow` = '1') ";
			// $sShow = " (`resources`.`iShow` = '1' OR `resources`.`iShow` = '0') ";

			if (!empty($mView)) {
				if (is_array($mView)) {
					$sWhere = " 0 ";
					foreach ($mView as $iView) {
						if (is_numeric($iView)) {
							$sWhere .= " OR `iView` = '$iView' ";
						}
					}

				} else if (is_numeric($mView)) {
					$sWhere = " `iView` = '$mView' ";

				} else {
					fnUpdateLog('fnTagsLinkedQuery(): iView NOT VALID', 0, '', 'E');
					return NULL; // ERRORE IMPREVISTO

				}

				
			} else {
				fnUpdateLog('fnTagsLinkedQuery(): iView EMPTY', 0, '', 'E');
				return NULL; // ERRORE IMPREVISTO

			}
		
		} else if ($sWhat == 'main-table') {
			$sShow = " (`resources`.`iShow` = '1') ";
			// $sShow = " (`resources`.`iShow` = '1' OR `resources`.`iShow` = '0') ";
			$sWhere = " 1 ";	

		}
		
		$sQuery = " SELECT `tags`.`iTag`, `resources`.`sDescription` AS `sDescription` ";
			
			global $aRESOURCES;
			
			if (isset($aRESOURCES[$sTagsType]['aFields']) && !empty($aRESOURCES[$sTagsType]['aFields'])) {
				foreach (($aRESOURCES[$sTagsType]['aFields']) as $sField) {
				
					// la variabile $sValue, definita qui di seguito, viene poi utilizzata nella
					// condizione IF della query (qualche riga più sotto.
					
					// se non è definito un valore per sDescriptionCompactView utilizzo in alternativa
					// il campo sDescription. In tutti gli altri casi lascio il valore vuoto.
					
					if ($sField == 'sDescriptionCompactView')
						$sValue = "`resources`.`sDescription`";
					else
						$sValue = "''";
						
					$sQuery .= ", IF (`$sField`.`sValue` IS NULL, $sValue, `$sField`.`sValue`) AS `$sField` ";
				}
			}
			
			$sQuery .= "	FROM `tags`
							LEFT OUTER JOIN `resources` ON `resources`.`id` = `tags`.`iTag` AND `resources`.`sType` = '$sTagsType' AND $sShow ";
			
			if (isset($aRESOURCES[$sTagsType]['aFields']) && !empty($aRESOURCES[$sTagsType]['aFields'])) {
				foreach (($aRESOURCES[$sTagsType]['aFields']) as $sField) {
					$sQuery .= " LEFT OUTER JOIN `properties` `$sField` ON `$sField`.`sSelectFrom` = 'resources' AND `$sField`.`iTable` = `resources`.`id` AND `$sField`.`sField` = '$sField' ";
				}
			}
			
		$sQuery .= " WHERE $sWhere AND `tags`.`sSelectFrom` = '$sViewSelectFrom' AND `tags`.`sApp` = '$sApp'
			GROUP BY `iTag`
			ORDER BY ".($bCompactView ? " `sDescriptionCompactView` "  : " `sDescription` " );		
		
		return $sQuery;		
	}	


	/**
	 *
	 * fnTagsAllQuery
	 *
	 * Query MySQL per estrarre tutti i tag per cui iShow == 1.
	 *
	 * Oltre ad estrarre i campi id e sDescription, estrae tutte le proprietà collegate definite
	 * nell'array $aRESOURCES[$sType]['aFields'].
	 *
	 * Se $bCompactView == true, i tag vengono visualizzati con l'etichetta 'breve' (`sDescriptionCompactView`).
	 *
	 */
	function fnTagsAllQuery ($sTagsType, $bCompactView=false) {
		
		global $aRESOURCES;

		$sQuery = " SELECT `resources`.`id` AS `iTag`, `resources`.`sDescription` AS `sDescription` ";
			
			if (isset($aRESOURCES[$sTagsType]['aFields']) && !empty($aRESOURCES[$sTagsType]['aFields'])) {
				foreach (($aRESOURCES[$sTagsType]['aFields']) as $sField) {
				
					// la variabile $sValue, definita qui di seguito, viene poi utilizzata nella
					// condizione IF della query (qualche riga più sotto.
					
					// se non è definito un valore per sDescriptionCompactView utilizzo in alternativa
					// il campo sDescription. In tutti gli altri casi lascio il valore vuoto.
					
					if ($sField == 'sDescriptionCompactView')
						$sValue = "`resources`.`sDescription`";
					else
						$sValue = "''";
						
					$sQuery .= ", IF (`$sField`.`sValue` IS NULL, $sValue, `$sField`.`sValue`) AS `$sField` ";
				}
			}
			
			$sQuery .= " FROM `resources` ";

			if (isset($aRESOURCES[$sTagsType]['aFields']) && !empty($aRESOURCES[$sTagsType]['aFields'])) {
				foreach (($aRESOURCES[$sTagsType]['aFields']) as $sField) {
					$sQuery .= " LEFT OUTER JOIN `properties` `$sField` ON `$sField`.`sSelectFrom` = 'resources' AND `$sField`.`iTable` = `resources`.`id` AND `$sField`.`sField` = '$sField' ";
				}
			}

		$sQuery .= " WHERE `resources`.`sType` = '$sTagsType' AND (`resources`.`iShow` = '1')
					 ORDER BY ".($bCompactView && (isset($aRESOURCES[$sTagsType]['aFields']) && in_array('sDescriptionCompactView', $aRESOURCES[$sTagsType]['aFields'])) ? " `sDescriptionCompactView` "  : " `sDescription` " );

		return $sQuery;
	}
	

	/**
	 *
	 * fnTagsSelInput
	 *
	 */
	 function fnTagsSelInput ($sName, $iView=0, $sViewItemLink='', $bCompactView=false) {
		
		global $sAPP;
		
		global $aVIEW;
		if (isset($aVIEW[$sViewItemLink]['sTagsType'])) {
			$sTagsType = $aVIEW[$sViewItemLink]['sTagsType'];
		} else  {
			die('ERROR: sTagsType not defined');
		}
		
		if (isset($aVIEW[$sViewItemLink]['sViewSelectFrom'])) {
			$sViewSelectFrom = $aVIEW[$sViewItemLink]['sViewSelectFrom'];
		} else  {
			die('ERROR: sViewSelectFrom not defined');
		}
		
		$html = '';

		// escludo dalle opzioni del <select> i tag già associati alla scheda
		$aExcludedOptions = array();
		if ($iView != 0)  {
			$sQuery = fnTagsLinkedQuery ('view', $iView, $sViewItemLink, $sAPP, $bCompactView);
			$rResult = custom_mysql_query($sQuery);
			if (mysql_num_rows($rResult) > 0) {
				while ($aRow = mysql_fetch_array($rResult)) {
					$aExcludedOptions[]=$aRow['iTag'];
				}
			}	 
		}

		$aOptions = array();
		$sQuery = fnTagsAllQuery ($sTagsType, $bCompactView);
		$rResult = custom_mysql_query($sQuery);
	   	if (mysql_num_rows($rResult) > 0) {
	   		while ($aRow = mysql_fetch_array($rResult)) {
	   			if (!in_array($aRow['iTag'], $aExcludedOptions)) {
		   			$sValue = ($bCompactView ? $aRow['sDescriptionCompactView'] : $aRow['sDescription']);
		       		$aOptions[$aRow['iTag']] = $sValue;
	   			}
	   		}
	   	}
   		if (empty($aOptions)) {
				$html .= "<select name='$sName' disabled><option value=''>Nessuna categoria disponibile</options></select>";
		} else { 
			$html .= "<select name='$sName' iView='$iView' sViewItemLink='$sViewItemLink'>";
			$html .= "<option value=''>Aggiungi categoria...</option>";
			foreach ($aOptions as $iTag => $sValue) {
				$html .= "<option value='$iTag'>&nbsp;".$sValue."&nbsp;</option>";
			}	
			$html .= "</select>";
		}

		return $html;	
	}


	/**
	 *
	 * fnTagsAddQuery
	 *
	 */
	function fnTagsAddQuery ($iTag, $iView, $sViewItemLink, $sApp) {
		
		global $aVIEW;
		
		if (isset($aVIEW[ $sViewItemLink]['sViewSelectFrom'])) {
			$sViewSelectFrom = $aVIEW[ $sViewItemLink]['sViewSelectFrom'];
		} else  {
			die('ERROR: sViewSelectFrom not defined');
		}	
		
		$sQuery = "INSERT IGNORE INTO `tags`	(`iView`, `iTag`, `sSelectFrom`, `sApp`)
			VALUES	('$iView', ABS('$iTag'), '$sViewSelectFrom', '$sApp')";
		return $sQuery;			
	}
	
	
	/**
	 *
	 * fnTagsRemoveQuery
	 *
	 */
	 function fnTagsRemoveQuery ($iTag, $iView, $sViewItemLink, $sApp) {
		
		global $aVIEW;
		
		if (isset($aVIEW[ $sViewItemLink]['sViewSelectFrom'])) {
			$sViewSelectFrom = $aVIEW[ $sViewItemLink]['sViewSelectFrom'];
		} else  {
			die('ERROR: sViewSelectFrom not defined');
		}	
		
		$sQuery = "DELETE FROM `tags`
			WHERE	`iView` = '$iView'
			AND 	`iTag` = ABS('$iTag')
			AND 	`sSelectFrom` = '$sViewSelectFrom'
			AND 	`sApp` = '$sApp'";
		return $sQuery;
	}


	/**
	 *
	 * fnTagsAction
	 *
	 */
	 function fnTagsAction ($sAction, $iTag, $iView, $sViewItemLink, $sApp) {
		
		global $aVIEW;
		
		if (isset($aVIEW[$sViewItemLink]['sViewSelectFrom'])) {
			$sViewSelectFrom = $aVIEW[$sViewItemLink]['sViewSelectFrom'];
		} else  {
			die('ERROR: sViewSelectFrom not defined');
		}	
			
		if ($iTag != 0) {

			if ($sAction == 'tags-remove' || $sAction == 'tags-remove-table' || $sAction == 'tags-remove-view') { 
				$sQuery = fnTagsRemoveQuery($iTag, $iView, $sViewItemLink, $sApp) ;
				$rResult = custom_mysql_query($sQuery, 'fnTagsRemoveQuery()');
				fnUpdateLog('TAG REMOVED', $iView, $sViewSelectFrom, 'I');
			
			} else if ($sAction == 'tags-add' || $sAction == 'tags-add-table' || $sAction == 'tags-add-view') { 	
				$sQuery = fnTagsAddQuery($iTag, $iView, $sViewItemLink, $sApp);
				$rResult = custom_mysql_query($sQuery, 'fnTagsAddQuery()');
				fnUpdateLog('TAG ADDED', $iView, $sViewSelectFrom, 'I');
			
			}
		}
		
		if ($sAction == 'tags-add' || $sAction == 'tags-add-table' || $sAction == 'tags-remove' || $sAction == 'tags-remove-table') {
			$html = fnTagsView('view', $iView, $sViewItemLink, '', '', $sApp, true, true, false);
		} else if ($sAction == 'tags-add-view' || $sAction == 'tags-remove-view') {
			$html = fnTagsView('view', $iView, $sViewItemLink, '', '', $sApp, false, true, true);
		}
		
		return  $html;
		
	}
	
	
	/**
	 *
	 * fnTagsCheck
	 *	
	 * Restituisce la variabile $bError: 'false' se ha trovato il $iTag, 'true' se non l'ha trovato.
	 *
	 */	 
	 function fnTagsCheck ($iTag, $sViewItemLink, $iShow=1, $iView=0, $sApp='') {
		
		global $aVIEW;

		if (isset($aVIEW[$sViewItemLink]['sTagsType'])) {
			$sTagsType =  $aVIEW[$sViewItemLink]['sTagsType'];
		} else  {
			die('ERROR: sTagsType not defined');
		}
		
		$bError = false;
		
		// controllo se esiste $iTag
		$sQuery = fnTagsCheckQuery($iTag, $sTagsType, $iShow);
		$rResult = custom_mysql_query($sQuery, 'fnTagsCheckQuery()');
		
		if (mysql_num_rows($rResult) < 1) {
			$bError = ($bError ? $bError : true);
		}
		
		if ($iView != 0 && $sApp != '') {
			
			if (isset($aTABLE[$sTable]['sViewItemLink']) &&
				isset($aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectFrom'])) {
				$sViewSelectFrom = $aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectFrom'];
			} else  {
				die('ERROR: sViewSelectFrom not defined');
			}	
			
			if (isset($aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectGroupBy']) &&
				isset($aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectGroupBy'])) {
				$sViewSelectGroupBy = $aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectGroupBy'];
			} else  {
				die('ERROR: sViewSelectGroupBy not defined');
			}	
			
			$bError = ($bError ? $bError : fnCheckView($iView, $sViewSelectFrom, $sViewSelectGroupBy, 'bError'));

		}
		
		return $bError;
	}
	
	
	/**
	 *
	 * fnTagsCheckQuery
	 *
	 */
	 function fnTagsCheckQuery ($iTag, $sTagsType, $iShow=1) {
		$sQuery = "SELECT * FROM `resources` WHERE `id`=ABS($iTag) AND `sType`='$sTagsType' AND `iShow`='$iShow'";
		return $sQuery;	
	}	
	
	
	/**
	 *
	 * fnTagsData4ExcelExport
	 *
	 */
	function fnTagsData4ExcelExport ($sTable, $sApp, $bCompactView=false) {
		
		global $aTABLE;
		global $aVIEW;

		if (isset($aTABLE[$sTable]['sViewItemLink']) &&
			isset($aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sTagsType'])) {
			$sTagsType =  $aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sTagsType'];
		} else  {
			die('ERROR: sTagsType not defined');
		}
		
		if (isset($aTABLE[$sTable]['sViewItemLink']) &&
			isset($aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectFrom'])) {
			$sViewSelectFrom = $aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectFrom'];
		} else  {
			die('ERROR: sViewSelectFrom not defined');
		}	
		
		if (isset($aTABLE[$sTable]['sTableSelectFrom'])) {
			$sTableSelectFrom =  $aTABLE[$sTable]['sTableSelectFrom'];
		} else  {
			die('ERROR: sTableSelectFrom not defined');
		}
		
		/**
		 * Per prima cosa vengono cercati tutti i tag associati ai record presenti in tabella, dopodichè
		 * viene creato un array in cui al campo 'id' di ciascun record della tabella associo i tag
		 * (sia quelli utilizzati sia quelli non utilizzati); questa funzione è stata creata per essere
		 * usata in table.php quando viene generato il file di excel.
		 *
		 */
		 
		// elenco di tutti i tag presenti nella tabella `resources` (fnTagsAllQuery trova tutti i
		// tag per cui iShow == 1)
		$aTagsData = array();
		$sQuery = fnTagsAllQuery($sTagsType, $bCompactView);
		$rResult = custom_mysql_query($sQuery, 'fnTagsAllQuery()');	
		
		if (mysql_num_rows($rResult) > 0) {
			
			$sQueryString = '';
			while ($aRow = mysql_fetch_array($rResult)) {
				$sQueryString .= ", IF (SUM(`resources`.`id`='".$aRow['iTag']."') > 0, 1, 0) AS `".($bCompactView ? $aRow['sDescriptionCompactView'] : $aRow['sDescription'])."` ";
			}

			// array id -> tag
			$sQuery = "SELECT `$sTableSelectFrom`.`id` AS `iView`
				$sQueryString 
				FROM `$sTableSelectFrom` 
				LEFT OUTER JOIN `tags` ON `$sTableSelectFrom`.`id` = `tags`.`iView` AND `tags`.`sSelectFrom` = '$sViewSelectFrom' AND `tags`.`sApp` = '$sApp' 
				LEFT OUTER JOIN `resources` ON `tags`.`iTag` = `resources`.`id` AND `resources`.`sType` = '$sTagsType' 
				GROUP BY `iView` 
				ORDER BY `iView` ASC";

			$rResult = custom_mysql_query($sQuery, 'fnTagsData4ExcelExport()');
			if (mysql_num_rows($rResult) > 0) {
				while ($aRow = mysql_fetch_assoc($rResult)) {
					$iView =  $aRow['iView'];
					unset($aRow['iView']);
					$aTagsData[$iView] = $aRow;
				}
			}
			
			return $aTagsData;
		}
	}

		
	/**
	 *
	 * fnJsTagRemoveClick
	 *
	 */
	 function fnJsTagsRemoveClick ($sName='tags-remove') {
		$sScript = 	"
			$('.".$sName."').click(function() {
				fnTagsRemove($(this));
			});		";
		return $sScript;	
	}	
	

	/**
	 *
	 * fnJsTagSelectChange
	 *
	 */
	 function fnJsTagsSelectChange ($sName='tags-sel-input') {
		$sScript = 	"
			$('select[name=\"".$sName."\"]').change(function() {
				if ($(this).attr('value')!='') {
					fnTagsAdd($(this).attr('value'), $(this));
				}
			});		";
		return $sScript;	
	}

	
	/**
	 *
	 * fnTagsFilter
	 *
	 * $sTag è la stringa contenuta nel parametro $_GET['sTag'] ('index.php? ... &sTag=17|25|33 ...').
	 *
	 */
	function fnTagsFilter ($sWhat, $sTag, $sTable, $sApp) {
		
		global $aTABLE;
		global $aVIEW;

		if (isset($aTABLE[$sTable]['sViewItemLink']) &&
			isset($aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sTagsType'])) {
			$sTagsType =  $aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sTagsType'];
		} else  {
			die('ERROR: sTagsType not defined');
		}
		
		if (isset($aTABLE[$sTable]['sViewItemLink']) &&
			isset($aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectFrom'])) {
			$sViewSelectFrom = $aVIEW[$aTABLE[$sTable]['sViewItemLink']]['sViewSelectFrom'];
		} else  {
			die('ERROR: sViewSelectFrom not defined');
		}
		
		$aTagsAll = array(); // array contenente tutti i tag
		$aTag = array(); // array contenente tutti i tag contenuti nel parametro $_GET['sTag']
		$sWhere = $sWhereAND = $sWhereOR = '';
		$sFirstRow = $sTableTitle = $sTableTitleValue = '';
		$sFirstRowLabel = '; categorie: ';
		$sDisplay = 'none';
		
		$sQuery = fnTagsAllQuery($sTagsType);
		$rResult = custom_mysql_query($sQuery, 'fnTagsAllQuery()');
		if (mysql_num_rows($rResult) > 0) {					
			while ($aRow = mysql_fetch_array($rResult)) {
				$aTagsAll[$aRow['iTag']] = $aRow;
			}
		}

		$aTagsAll[0]['iTag'] = 0;
		$aTagsAll[0]['sDescription'] = 'Nessuna Categoria';
		$aTagsAll[0]['sDescriptionCompactView'] = 'Nessuna';
		$aTagsAll[0]['sStyle'] = '';	
	
		if ($sTag != '') {
			$aTag = explode ('|', $sTag);
			if (count($aTag) > 0) {
				
				$sFirstRow .= $sFirstRowLabel;
				
				foreach ($aTag as $iTag) {
				
					if ($iTag != '' && is_numeric($iTag)) {
						
						if ($iTag != 0) {
						
							if (isset($aTagsAll[abs($iTag)])) {
								
								$sDisplay = '';
								
								// ($iTag > 0):	includo
								// ($iTag < 0):	escludo
								
								if ($iTag > 0) {
									$sWhereOR .= " ".(!empty($sWhereOR) ? " OR " : "")." `id` IN (SELECT `iView` FROM `tags` WHERE `iTag`=ABS('$iTag') AND `sSelectFrom`='$sViewSelectFrom' AND `sApp`='$sApp') ";
								
								} else if ($iTag < 0) {
									$sWhereAND .= " ".(!empty($sWhereAND) ? " AND " : "")." `id` NOT IN (SELECT `iView` FROM `tags` WHERE `iTag`=ABS('$iTag') AND `sSelectFrom`='$sViewSelectFrom' AND `sApp`='$sApp') ";
								
								} 
								
								$aTagsAll[abs($iTag)]['bTableTitleShow'] = true;
									$sFirstRow .= $aTagsAll[abs($iTag)]['sDescription'].($iTag < 0 ? " (esclusa)" : "").", ";
								}
								
							} else if ($iTag == 0) {
							
								$sDisplay = '';
								$sWhereOR .= " ".(!empty($sWhereOR) ? " OR " : "")." `id` NOT IN (SELECT `iView` FROM `tags` WHERE `sSelectFrom`='$sViewSelectFrom' AND `sApp`='$sApp' GROUP BY `iView`) ";
								$aTagsAll[0]['bTableTitleShow'] = true;
								$sFirstRow .= $aTagsAll[abs($iTag)]['sDescription'].", ";
								
							} 
							
						}
						
					}
					
					$sFirstRow = ($sFirstRow==$sFirstRowLabel ? '' : substr_replace($sFirstRow, '', -2)." ");
					
				}
			}
			
			$sWhere = (!empty($sWhereOR) ? " AND ($sWhereOR) " : '').(!empty($sWhereAND) ? " AND ($sWhereAND) " : '');
			
			foreach ($aTagsAll as $iTag => $aTag) {
				$sTableTitleValue .= "<span class='table-title-value' id='".$aTag['iTag']."' style='display:".
				(isset($aTagsAll[$aTag['iTag']]['bTableTitleShow']) && $aTagsAll[$aTag['iTag']]['bTableTitleShow'] ? '' : "none").
				";'>";
				$sTableTitleValue .= "<span class='tags-table-title' style='".$aTag['sStyle']."'>".$aTag['sDescription'] ."</span>";
				$sTableTitleValue .= "&nbsp;</span>";
			}
		
			$sTableTitle .= "<span class='table-title-more' id='table-title-tags' style='display: $sDisplay'> &raquo; Categorie: $sTableTitleValue</span>";
			
			switch ($sWhat) {
				case 'sTableTitle':
					return $sTableTitle;
					break;
				case 'sWhere':
					return $sWhere;
					break;		
				case 'sFirstRow':
					return $sFirstRow;
					break;	
				default:
					return array(	'sTableTitle'	=>	$sTableTitle,
									'sWhere'		=>	$sWhere,
									'sFirstRow'		=>	$sFirstRow		);
					break;
			}

	}

?>